import { ref, watch, nextTick, computed } from 'vue'
export default function useFixed(props) {
  const TITLE_HEIGHT = 30
  const groupRef = ref(null)
  const listHeights = ref([])
  const scollY = ref(0)
  const currentIndex = ref(0)
  const distance = ref(0)
  const fixedTitle = computed(() => {
    if (scollY.value < 0) {
      return ''
    }
    const currentGroup = props.data[currentIndex.value]
    return currentGroup ? currentGroup.title : ''
  })
  
  const fixStyle = computed(() => {
    const distanceVal = distance.value
    const diff = (distanceVal > 0 && distanceVal < TITLE_HEIGHT) ?distanceVal - TITLE_HEIGHT:0
    return {
      transform: `translate3d(0,${diff}px,0)`
    }
  })
  // 有数据再进行计算高度 才会没有问题
  // 监听响应式对象 使用 () => props.data
  watch(() => props.data, async () => {
    await nextTick()
    calulate()
  })
  // watch 的第二个参数 的两个参数 newValue oldValue
  watch(scollY, (newY) => {
    const listHeightVal = listHeights.value
    for (let i = 0; i < listHeightVal.length - 1; i++) {
      const heightTop = listHeightVal[i]
      const heightBottom = listHeightVal[i + 1]
      if (newY >= heightTop && newY <= heightBottom) {
        currentIndex.value = i
        distance.value = heightBottom - newY
      }
    }
    return ''
  })
  function calulate() {
    const list = groupRef.value.children
    // 这个list 是一个类别的歌手的list 
    let height = 0
    listHeights.value.length = 0
    listHeights.value.push(height)
    for (let i = 0; i < list.length; i++) {
      // element的clientHeight 是 盒元素 content 加 padding
      height += list[i].clientHeight
      listHeights.value.push(height)
    }
  }
  function onScroll(pos) {
    scollY.value = -pos.y
  }
  return {
    groupRef,
    onScroll,
    fixedTitle,
    fixStyle,
    currentIndex
  }
}